import { useEffect, useState } from 'react';
// import monaco from 'monaco-editor';
import MonacoEditor, { useMonaco } from '@monaco-editor/react';
import SQLKeyword from './SQLkeyword.json';
import * as MonacoNameSpace from 'monaco-editor';

const M: React.FC = function () {
  const monaco = useMonaco();
  const [suggestionRecord, setSuggestionRecord] = useState<{ [k: string]: MonacoNameSpace.IDisposable }>({});
  const [code, setCode] = useState<string | undefined>('SELECT user FROM acction_user');

  function registerHint(key: string, hints: string[]) {
    if (monaco) {
      if (key in suggestionRecord) {
        suggestionRecord[key]?.dispose();
      }

      const suggestion = monaco.languages.registerCompletionItemProvider('sql', {
        provideCompletionItems(model, position) {
          const word = model.getWordUntilPosition(position);
          return {
            suggestions: hints.map(item => {
              return {
                insertText: item,
                kind: monaco.languages.CompletionItemKind.Keyword,
                label: item,
                range: {
                  startLineNumber: position.lineNumber,
                  endLineNumber: position.lineNumber,
                  startColumn: word.startColumn,
                  endColumn: word.endColumn,
                },
              };
            }),
            incomplete: true,
          };
        },
        triggerCharacters: [':'],
      });

      if (key !== ':default') {
        setSuggestionRecord({ ...suggestionRecord, [key]: suggestion });
      }

      return suggestion;
    }
  }

  function unRegisterHint(key: string) {
    if (monaco && key in suggestionRecord) {
      suggestionRecord[key]?.dispose();
    }
  }

  function onMount(editor: MonacoNameSpace.editor.IStandaloneCodeEditor) {
    editor.onDidChangeModelContent(console.log);
    editor.onKeyDown(console.log);
    // editor.onDidChangeModel(console.log);
  }

  useEffect(() => {
    let sqlSuggestion = registerHint(':default', SQLKeyword);
    return () => {
      sqlSuggestion && sqlSuggestion.dispose();
    };
  }, [monaco]);

  return (
    <div style={{ height: 600, width: '100%' }}>
      <a
        onClick={() => {
          registerHint('car', ['toyota', 'honda', 'vw']);
        }}
      >
        手动注册
      </a>
      <a onClick={() => unRegisterHint('car')}>手动卸载</a>
      <MonacoEditor language={'sql'} theme="vs-dark" value={code} onChange={setCode} onMount={onMount} />
    </div>
  );
};

M.displayName = 'M';
export default M;
